<template>
	<el-form size="large" class="login-content-form">
		<el-form-item class="login-animation1">
			<el-input text placeholder="用户名" v-model="state.ruleForm.user_name" clearable autocomplete="new-password">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-input :type="state.isShowPassword ? 'text' : 'password'" placeholder="密码" v-model="state.ruleForm.password" autocomplete="new-password">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button class="login-content-submit" round v-waves @click="state.dialog.isShowDialog = true"  v-if="state.loginInfos.length">
				<span>快捷登录</span>
			</el-button>
			<el-button type="primary" class="login-content-submit" round v-waves @click="onSignIn()" style="margin-left: 0;"  :loading="state.loading.signIn">
				<span>登 录</span>
			</el-button>
		</el-form-item>
		<div class="font12 mt30 login-animation4 login-msg">
			* 温馨提示：建议使用谷歌、Microsoft Edge，版本 79.0.1072.62 及以上浏览器，360浏览器请使用极速模式
		</div>
	</el-form>
	<el-dialog v-model="state.dialog.isShowDialog" width="400px" append-to-body>
		<template #header="{ close, titleId, titleClass }">
			<div class="my-header">
				<h5 :id="titleId" :class="titleClass">快捷登录</h5>
			</div>
		</template>
		<div v-for="(item,index) in state.loginInfos" :key="index" class="infologin">
			<div class="leftinfo">
				<el-avatar :src="state.VITE_IMG_URL + item.picture" class="mr10" :size="40">
					<img :src="chatHealthTou" />
				</el-avatar>
				<span>{{ item.nickname || item.user_name }}</span>
			</div>
			<div>
				<el-button size="small" type="primary" @click="onSignIn(item)" :loading="item.loading">登录</el-button>
				<el-button size="small" type="danger" @click="deleteInfo(index)">删除</el-button>
			</div>
		</div>
	</el-dialog>
</template>

<script setup name="loginAccount">
import { reactive, computed,onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session,Local } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import { useLoginApi } from '/@/api/login/index';
import { useUserInfo } from '/@/stores/userInfo';
import Ctypto from '/@/utils/crypto.js';
import chatHealthTou from '/@/assets/error_tou.png'
// 定义变量内容
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const state = reactive({
	VITE_IMG_URL:import.meta.env.VITE_IMG_URL,
	loginInfos:[],
	isShowPassword: false,
	ruleForm: {
		user_name: '',
		password: '',
	},
	loading: {
		signIn: false,
	},
	dialog: {
		isShowDialog: false,
	},
});
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录
const onSignIn = async (info = null) => {
	console.log(info);
	if(info){
		info.loading = true
		state.ruleForm = {
			user_name: info.user_name,
			password: info.password,
		}
	}else{
		state.loading.signIn = true;
	}
	try {
		let res = await useLoginApi().signIn(state.ruleForm)
		state.loading.signIn = true;
		Session.set('token', res.data.access_token);

		var strings = res.data.access_token.split(".");//通过split()方法将token转为字符串数组
		var userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/"))))); 
		if(userinfo && userinfo.extend){
			let userinfoData = JSON.parse(JSON.stringify(userinfo.extend));
			console.log(userinfoData);
			
			let infoIndex = state.loginInfos.findIndex(item => item.user_name == state.ruleForm.user_name)
			let info = {
				user_name: state.ruleForm.user_name,
				password: state.ruleForm.password,
				nickname: userinfoData.nickname,
				picture: userinfoData.picture
			}
			if (infoIndex == -1) {
				if (state.loginInfos.length >= 5) {
					state.loginInfos.pop();
				}
			} else {
				state.loginInfos.splice(infoIndex, 1);
			}
			state.loginInfos.unshift(info);
			Local.set('loginInfo', state.loginInfos);

			userinfoData.password = Ctypto.encryptData(state.ruleForm.password);
			useUserInfo().setUserInfos(userinfoData)
			Local.set('userInfo', userinfoData);
		}

		if (!themeConfig.value.isRequestRoutes) {
			// 前端控制路由，2、请注意执行顺序
			const isNoPower = await initFrontEndControlRoutes();
			signInSuccess(isNoPower);
		} else {
			// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			const isNoPower = await initBackEndControlRoutes();
			// 执行完 initBackEndControlRoutes，再执行 signInSuccess
			signInSuccess(isNoPower);
		}
	} catch (error) {
		if(info){
			let infoIndex = state.loginInfos.findIndex(item => item.user_name == state.ruleForm.user_name)
			if(infoIndex != -1){
				deleteInfo(infoIndex)
			}
		}
	}
	if(info){
		info.loading = false
	}else{
		state.loading.signIn = false;
	}
};
const deleteInfo = (index) =>{
	state.loginInfos.splice(index, 1);
	Local.set('loginInfo', state.loginInfos);
	if(state.loginInfos.length == 0){
		state.dialog.isShowDialog = false
	}
}
// 登录成功后的跳转
const signInSuccess = (isNoPower) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: route.query?.redirect,
				query: Object.keys(route.query?.params).length > 0 ? JSON.parse(route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = '欢迎回来！';
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	state.loading.signIn = false;
};
// 页面加载时
onMounted(() => {
	state.loginInfos = Local.get('loginInfo') || [];
});
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
}
.infologin{
	&:last-of-type{
		border: none;
	}
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px 0;
	border-bottom: 1px solid #333;
	.leftinfo{
		display: flex;
		align-items: center;
	}
}
</style>
